package flex.cc.single.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * @author R
 * @2022年3月31日  19:52:51
 * 单项类签名生成与验签
 */
public class SingleSignUtil {
	private static final Logger logger = LoggerFactory.getLogger(SingleSignUtil.class);
    
    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     * 
     * @param data 待签名数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名
     * @throws Exception
     * @since JDK 1.7
     */
    public static String generateSignature(final Map<String, Object> data, String key) throws Exception {

        Map<String, String> params = filterBlank(data);
        Set<String> keySet = params.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        JSONObject jsonObj = new JSONObject();
        for (String k : keyArray) {
            if (k.equals("sign")) {
                continue;
            }
            if (k.equals("UserCard")||k.equals("userInfo")||k.equals("businessInfo")||k.equals("thridPartyInfo")) {
            	String JsonStr = params.get(k).trim();
            	JSONObject JsonObj = JSONObject.parseObject(JsonStr);
            	Map<String, Object>  map = JsonObj.toJavaObject(Map.class);
            	jsonObj.put(k,map);
            }else{
            	jsonObj.put(k, params.get(k).trim());
            }
            
        }
        String sbStr = jsonObj.toJSONString();
        
        logger.info("before sign: ---------"+(key+sbStr));
        String sign = DigestUtils.md5Hex((key+sbStr).getBytes("UTF-8"));
        return sign;
    }


    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     * 
     * @param data Map类型数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名是否正确
     * @since JDK 1.7
     */
    public static boolean isSignatureValid(Map<String, Object> data, String key) {
        if (!data.containsKey("sign")) {
            return false;
        }
        String sign = data.get("sign").toString();
        logger.info("request sign: "+ sign);
        try {
        	logger.info("系统开始生成 sign: ");
        	String newSign = generateSignature(data, key);
        	logger.info("系统生成 sign: "+ newSign);
        	System.out.println("系统生成 sign: "+ newSign);
            return newSign.equals(sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * filterBlank:过滤请求报文中的空字符串或者空字符串
     * 
     * @param contentData 待过滤的数据
     * @return
     * @since JDK 1.7
     */
    public static Map<String, String> filterBlank(Map<String, Object> contentData) {

        Map<String, String> submitFromData = new HashMap<String, String>();
        Set<String> keyset = contentData.keySet();
        for (String key : keyset) {
            String value = contentData.get(key).toString();
            if (!StringUtils.isBlank(value)) {
                submitFromData.put(key, value.trim());
            }
        }
        return submitFromData;
    }


    public static Map<String, Object> filterBlankObj(Map<String, Object> contentData) {

        Map<String, Object> submitFromData = new HashMap<String, Object>();
        Set<String> keyset = contentData.keySet();
        for (String key : keyset) {
            Object value = contentData.get(key);
            if (null!=value&&!StringUtils.isBlank(value.toString())) {
                submitFromData.put(key, value.toString().trim());
            }
        }
        return submitFromData;
    }
}
